<?php
class Cp_AttachmentsController extends Pidguin_Controller_Cp_Action
{
	public function init()
	{
		$this->_disableView();
	}
	public function uploadAttachmentAction()
	{
		if (!$this->_getParam('sid')) {
			throw new Zend_Controller_Action_Exception('SID is not set');
		}
		$select = Model_Client::getInstance()->select();
		$select->where(Model_Client::getDefaultAdapter()->quoteInto('sid = ?', $this->_getParam('sid')));
		$row = Model_Client::getInstance()->fetchRow($select);
		if (!$row) {
			throw new Zend_Controller_Action_Exception('SID is not found');
		}
		$targetFolder = ROOT_DIR . DS . 'Misc' . DS . 'Uploads';
		$imageTypes = array('jpg', 'jpeg', 'gif', 'png');
		$imageFileSize = 20 * 1024 * 1024;
		$audioTypes = array('mp3');
		$audioFileSize = 40 * 1024 * 1024;
		$videoTypes = array('avi', 'mp4', '3gp', 'mpeg', 'mov', 'flv', 'wmv');
		$videoFileSize = 50 * 1024 * 1024;
		$docTypes = array('txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rtf', 'pdf');
		$docFileSize = 10 * 1024 * 1024;
		$otherTypes = array('rar', 'psd');
		$otherFileSize = 30 * 1024 * 1024;
		$fileParts = pathinfo($_FILES['Filedata']['name']);
		$fileType = null;
		$error = null;
		$fileParts['extension'] = strtolower($fileParts['extension']);
		if (in_array($fileParts['extension'], $imageTypes)) {
			if ($_FILES['Filedata']['size'] < $imageFileSize) {				
				$fileType = 'image';
			} else {
				$error = 'Превышен допустимый размер файла.';
			}
		} elseif (in_array($fileParts['extension'], $audioTypes)) {
			if ($_FILES['Filedata']['size'] < $audioFileSize) {
				$fileType = 'audio';
			} else {
				$error = 'Превышен допустимый размер файла.';
			}
		} elseif (in_array($fileParts['extension'], $videoTypes)) {
			if ($_FILES['Filedata']['size'] < $videoFileSize) {
				$fileType = 'video';
			} else {
				$error = 'Превышен допустимый размер файла.';
			}
		} elseif (in_array($fileParts['extension'], $docTypes)) {
			if ($_FILES['Filedata']['size'] < $docFileSize) {
				$fileType = 'doc';
			} else {
				$error = 'Превышен допустимый размер файла.';
			}
		} elseif (in_array($fileParts['extension'], $otherTypes)) {
			if ($_FILES['Filedata']['size'] < $otherFileSize) {
				$fileType = 'other';
			} else {
				$error = 'Превышен допустимый размер файла.';
			}
		} else {
			$fileType = null;
			$error = 'Неизвестный формат файла.';
		}
		if ($error) {
			$this->_helper->json(array('error'=>$error));
		}
		$_fFileName = new Zend_Filter_Alnum();
		$fileName = $_fFileName->filter($_FILES['Filedata']['name']);
		$fileName = strtr($fileName, array($fileParts['extension'] => ''));
		$row = Model_Attachments::getInstance()->createRow();
		$row->name = $fileName;
		$url = '/Misc/Uploads/' . $fileType . '/' . md5($fileName . '.' . $fileParts['extension']) . '.' . $fileParts['extension'];
		$row->type = $fileType;
		$row->url = $url;
		$realPath = $targetFolder . DS . strtolower($fileType) . DS . md5($fileName . '.' . $fileParts['extension']) . '.' . $fileParts['extension'];
		$row->realpath = $realPath;
		$row->hash = md5($realPath);
		$row->created = date('Y-m-d H:i:s', time());
		if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $realPath)) {
			$row->save();
			$this->_helper->json(array('url' => $row->url, 'id' => $row->id, 'type' => $fileType, 'description' => $row->description));
		} else {
			$this->_helper->json(array('error' => 'При сохранении файла возникли ошибки'));
		}
	}
	
	public function deleteAttachAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('ID is not set');
		}
		
		$select = Model_Attachments::getInstance()->select();
		$select->where(Model_Attachments::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = Model_Attachments::getInstance()->fetchRow($select);
		
		if (!$row) {
			throw new Zend_Controller_Action_Exception('File is not found');
		}
		
        if (is_file($row->realpath)) {
            unlink($row->realpath);
        }
        
		$row->delete();
		$this->_helper->json(array('status' => 'ok'));
	}
}
